<template>
  <div class="addAddress">
    <!-- 头部 -->
    <van-nav-bar title="添加地址" left-text="返回" :fixed="true" left-arrow @click-left="onClickLeft" />

    <van-address-edit
      :area-list="areaList"
      show-postal
      show-set-default
      :search-result="searchResult"
      @save="onSave"
      @change-detail="onChangeDetail"
    />
  </div>
</template>


<script>
import { Toast } from "vant";
import areaList from "./../../../../config/area";
import { addUserAddress } from "./../../../../service/api/index";
import { mapState } from "vuex";
import PubSub from "pubsub-js";

export default {
  name: "",

  data() {
    return {
      areaList: areaList,
      searchResult: []
    };
  },
  computed: {
    ...mapState(["userInfo"])
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    async onSave(content) {
      // console.log(content);
      // console.log(this.userInfo.token);

      if (this.userInfo.token) {
        // alert("hahah ");
        let result = await addUserAddress(
          this.userInfo.token,
          content.name,
          content.tel,
          content.province + content.city + content.county,
          content.addressDetail,
          content.postalCode,
          content.isDefault,
          content.province,
          content.city,
          content.county,
          content.areaCode
        );
        // console.log(result);

        if (result.success_code === 200) {
          //登录成功
          Toast({
            message: "添加地址成功!",
            duration: 500
          });
          // 添加成功返回
          this.$router.back();
          // 发起通知
          PubSub.publish("backToMyaddress");
        } else {
          Toast({
            message: "没填邮编会导致添加地址失败!!",
            duration: 500
          });
        }
      }
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: "黄龙万科中心",
            address: "杭州市西湖区"
          }
        ];
      } else {
        this.searchResult = [];
      }
    }
  }
};
</script>


<style lang="less" scoped>
.addAddress {
  position: absolute;
  top: 4rem;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #f5f5f5;
  z-index: 9999;
}
</style>